import memoize from 'memoize-one';
import React from "react";
import {Button, Checkbox, Dropdown, Menu, message, Modal,} from "antd";
import FileCard from "../../utils/center/FileCard";
import {
    CloudDownloadOutlined,
    DeleteOutlined,
    DownCircleTwoTone,
    FileAddOutlined,
    FolderAddOutlined,
    ReloadOutlined,
    ShareAltOutlined
} from "@ant-design/icons";
import '../../assets/center/MiddleContent.css';

// const cardsPerPage = 24;
const MenuItem = Menu.Item;

export default class MiddleContent extends React.PureComponent{
    constructor(props) {
        super(props);
        this.state = {
            checkedSum: 0,
            isMenuHide: true,
            isCardMenu: false,
            clientX: 0,
            clientY: 0,
            CopyInfos: [],
            // page: 1
        }
        this.CardElems = [];
        this.CardItems = null;
    }
    // filter = memoize(
    //     (FileInfos, page) => FileInfos.slice((page-1)*cardsPerPage, page*cardsPerPage)
    // );
    overflowX = memoize(
        (width, clientX) => width - clientX < 127
    );
    overflowY = memoize(
        (height, clientY, isCardMenu) => {
            let res = height - clientY < (isCardMenu ? 340 : 144)
            console.log(height, clientY, isCardMenu, res);
            return res;
        }
    );
    handleCheckedChange = (add)=>{
        if(add){
            this.setState({checkedSum: this.state.checkedSum+1});
        }else{
            this.setState({checkedSum: this.state.checkedSum-1});
        }
    }

    handlePageChange = (page)=>{
        this.setState({page});
    }
    handleMouseOnCards = (on)=>{
        this.setState({mouseOnCards: on});
    }
    tellNameRepeat = (newName)=>{
        for (const {name} of this.props.FileInfos)
            if(name === newName){
                throw Error('文件名重复')
            }
    }
    onAllChange = (e)=>{
        if(e.target.checked){
            this.setState({checkedSum: this.props.FileInfos.length});
        }
        else{
            this.setState({checkedSum: 0});
        }
    }
    getCheckedInfos = async ()=>
        await Promise.all(this.CardElems.map(
            elem => elem.state.check? new Promise(elem.getDownloadURL): 0
        ))
    checkedDownload = this.props.asyncDisableCall(async ()=> {
        try {
            const infos = await this.getCheckedInfos();
            const a = document.createElement('a');
            document.body.appendChild(a);
            for (const [url, name] of infos) {
                a.href = url;
                a.download = name;
                a.click();
            }
            document.body.removeChild(a);
        } catch (e) {
            Modal.error({
                title: '批量文件下载',
                content: `失败：${e}`
            });
        }
    });
    checkedShare = this.props.asyncDisableCall(async ()=>{
        try {
            const urls = await this.getCheckedURL();
            Modal.success({
                title: '批量文件分享',
                content: (<span>
                    链接：
                    {urls.map((url, index)=>
                        (<a href={url} download={this.CardElems[index].state.FileInfo.name}>{url}</a>)
                    )}
                </span>)
            })
        } catch (e) {
            Modal.error({
                title: '批量文件分享',
                content: `失败：${e}`
            });
        }
    });
    checkedDelete = this.props.asyncRefreshCall(async ()=>{
        const Message = await Promise.all(this.CardElems.map((elem)=>{
            if (elem.state.check)
                return new Promise(elem.onDelete);
            else
                return 0;
        })).catch(e=>e);
        if(Message.succeed) {
                message.success(`文件批量删除成功`);
        }else {
                message.error(`文件批量删除失败：${Message.msg}`);
        }
    });
    handleContentMouseUp = (e)=>{
        window.oncontextmenu = ()=>false;
        if (e.button === 2) {
            this.setState({
                isCardMenu: false,
                isMenuHide: false,
                clientX: e.clientX, clientY: e.clientY
            });
        }
        if (e.button === 0) {
            this.setState({isMenuHide: true});
        }
    }
    handleCardMenuCall = (menu, e)=>{
        window.oncontextmenu = () => false;
        this.CardItems = menu;
        this.setState({isCardMenu: true ,isMenuHide: false, clientX: e.clientX, clientY: e.clientY});
    }
    menuForMulti = (
        <Menu>
            <MenuItem key={1} onClick={this.checkedDownload} icon={<CloudDownloadOutlined/>}>批量下载</MenuItem>
            <MenuItem key={2} onClick={this.checkedShare} icon={<ShareAltOutlined/>}>批量分享</MenuItem>
            <MenuItem key={3} onClick={this.checkedDelete} icon={<DeleteOutlined/>} danger>批量删除</MenuItem>
        </Menu>
    );
    // componentDidUpdate(prevProps, prevState, snapshot) {
    //     if(prevProps.FileInfos !== this.props.FileInfos) {
    //         console.log('MiddleContent just Updated');
    //         this.setState({FileInfos: this.props.FileInfos});
    //     }
    // }

    render() {
        // const currentFileInfos = this.filter(this.props.FileInfos, this.state.page);
        const FileInfosLength = this.props.FileInfos.length;

        const overflowX = this.overflowX(window.innerWidth, this.state.clientX),
              overflowY = this.overflowY(window.innerHeight, this.state.clientY, this.state.isCardMenu);
        return (
            <div className='content' onMouseUp={this.handleContentMouseUp}>
                <div className='container'>
                    {this.props.FileInfos.map((item, index)=>
                        <FileCard FileInfo={item}
                                  checkedSum={this.state.checkedSum}
                                  fileSum={FileInfosLength}
                                  handleCardMenuCall={this.handleCardMenuCall}
                                  handleMouseOnCards={this.handleMouseOnCards}
                                  handleCheckChange={this.handleCheckedChange}
                                  onEnterFolder={this.props.onEnterFolder}
                                  asyncRefreshCall={this.props.asyncRefreshCall}
                                  asyncDisableCall={this.props.asyncDisableCall}
                                  tellNameRepeat={this.tellNameRepeat}
                                  ref={elem =>this.CardElems[index] = elem}
                        />
                    )}
                </div>
                {/*<div className='page'>*/}
                {/*    <Pagination simple defaultPageSize={24} total={FileInfosLength} onChange={this.handlePageChange}/>*/}
                {/*</div>*/}
                <div className='multi'>
                    <Checkbox checked={this.state.checkedSum===FileInfosLength}
                              onChange={this.onAllChange}
                              indeterminate={this.state.checkedSum&&this.state.checkedSum<FileInfosLength}
                    >
                        全选
                    </Checkbox>
                    {
                        !!this.state.checkedSum &&
                        <span>
                        - 已选择 {this.state.checkedSum}/{FileInfosLength}
                            <Dropdown overlay={this.menuForMulti} trigger='hover' placement='topLeft'>
                            <Button type='link'
                                    icon={<DownCircleTwoTone rotate={180}/>}
                                    size='middle'
                            />
                            </Dropdown>
                        </span>
                    }
                </div>
                    <Menu
                        className='rightClickMenu'
                        hidden={this.state.isMenuHide}
                        style={{
                            left: this.state.clientX+'px', top: this.state.clientY+'px',
                            transform: `translate(${overflowX?'-100%':0},${overflowY?'-100%':0})`,
                        }}
                    >
                        {this.state.isCardMenu? this.CardItems : <>
                            <MenuItem icon={<ReloadOutlined/>} onClick={this.props.onRefresh} key={1}>刷 新</MenuItem>
                            <MenuItem icon={<FolderAddOutlined/>} onClick={this.props.onCreatFolder} key={2}>新建文件夹</MenuItem>
                        </>}
                        <MenuItem disabled={!this.state.hasCopy} icon={<FileAddOutlined />} key={3}>粘 贴</MenuItem>
                    </Menu>
            </div>);
    }
}